package com.zhang.webadmin.service;

import com.zhang.webadmin.pojo.AclPermission;
import com.zhang.webadmin.pojo.AclUser;
import jakarta.annotation.Resource;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class UserService implements UserDetailsService {

    @Resource
    private AclUserService aclUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        AclUser aclUser = aclUserService.lambdaQuery()
                .eq(AclUser::getLoginName, username)
                .one();
        if (aclUser == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }

        List<AclPermission> permissionList = aclUserService.queryPermission(aclUser.getId());
        List<String> strings = permissionList.stream()
                .filter(item -> item.getCode() != null && !item.getCode().isBlank())
                .map(AclPermission::getCode)
                .toList();
        if (!strings.isEmpty()) {

            aclUser.setAuthorities(AuthorityUtils.createAuthorityList(strings));
        }

        return aclUser;
    }
}
